package org.zfes.snowier.xyz.live;

import java.util.Map;
import java.util.Optional;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.zfes.snowier.common.socket.data.MsgData;
import org.zfes.snowier.common.socket.device.sender.INettyMsgSender;
import org.zfes.snowier.core.util.UUIDUtil;
import org.zfes.snowier.core.util.ZStrUtil;
import org.zfes.snowier.xyz.live.dto.LiveStatus;
import com.google.common.collect.Maps;
@Component
public class VideoStatusSimpleManager implements IVideoStatusManager, InitializingBean {

	@Autowired INettyMsgSender nettyMsgSender;
	
	//<deviceNum#channelId,VideoStatus>
	private static final Map<String,LiveStatus> liveStatusMap = Maps.newConcurrentMap();
	
	
	@Override
	public void afterPropertiesSet() throws Exception {
	//	liveChannelReady("FF_505152069029", "0001", "liveId01");
	}
	
	
	@Override
	public boolean isChannelOnLive(String deviceNum, String channelId) {
		LiveStatus lst=liveStatusMap.get(constructKey( deviceNum,  channelId));
		if(lst==null) {
			return false;
		}
		return Byte.valueOf("1").equals(lst.getStatus());
	}
	
	
	@Override
	public Optional<LiveStatus> getLiveChannelStatus(String deviceNum, String channelId) {
		if(ZStrUtil.hasNoText(deviceNum)||ZStrUtil.hasNoText(channelId)) {
			return Optional.empty();
		}
		return Optional.ofNullable(liveStatusMap.get(constructKey( deviceNum,  channelId)));
	}
	@Override
	public void setLiveChannelStatus(String deviceNum, String channelId, String liveId , Byte status) {
		if(ZStrUtil.hasNoText(deviceNum)||ZStrUtil.hasNoText(channelId)||ZStrUtil.hasNoText(liveId)||status==null) {
			return ;
		}
		liveStatusMap.put(constructKey( deviceNum,  channelId), new LiveStatus(status,liveId));
		//System.out.println("liveStatusMap:"+liveStatusMap);
	}
	
	@Override
	public void liveChannelStart(String deviceNum, String channelId, String liveId) {
		if(ZStrUtil.hasNoText(deviceNum)||ZStrUtil.hasNoText(channelId)||ZStrUtil.hasNoText(liveId)) {
			return ;
		}
		liveStatusMap.put(constructKey( deviceNum,  channelId), new LiveStatus( Byte.valueOf("1"),liveId));
		//System.out.println("liveStatusMap:"+liveStatusMap);
	}
	
	@Override
	public void liveChannelStop(String deviceNum, String channelId) {
		if(ZStrUtil.hasNoText(deviceNum)||ZStrUtil.hasNoText(channelId)) {
			return ;
		}
		liveStatusMap.remove(constructKey( deviceNum,  channelId));
		 String msgId = UUIDUtil.fastUUID();
		 nettyMsgSender.sendToDevice(deviceNum, 
	    			MsgData.ok()
	    			.setCmdCode(Cmd.stoptLive)
	    			.setCmdDirect(Byte.valueOf("1"))
	    			.setCmdUid(msgId)
	    			.setDeviceNum(deviceNum)
	    			.put("channelId", channelId).put("deviceNum", deviceNum));
		
	}

	private String constructKey(String deviceNum, String channelId) {
		
		return deviceNum+"#"+channelId;
	}
	
	
}
